package com.lfy.modules.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lfy.encrypt.EncryptUtil;
import com.lfy.modules.blog.domain.HomeDetail;
import com.lfy.modules.blog.domain.dto.user.PwdDTO;
import com.lfy.modules.blog.domain.dto.user.UserDTO;
import com.lfy.modules.blog.domain.dto.user.ModifyFreezeUserDTO;
import com.lfy.modules.blog.domain.dto.user.ModifyUserRoleDTO;
import com.lfy.modules.blog.domain.group.SaveGroup;
import com.lfy.modules.blog.domain.group.UpdateGroup;
import com.lfy.modules.blog.domain.vo.auth.UserListVO;
import com.lfy.modules.blog.service.HomeDetailService;
import com.lfy.modules.common.anno.Authentication;
import com.lfy.modules.common.anno.AutoUser;
import com.lfy.modules.common.anno.NoNeedLogin;
import com.lfy.modules.common.custom.constants.PageConstant;
import com.lfy.modules.common.domain.BaseEnum;
import com.lfy.modules.common.domain.PageResultVO;
import com.lfy.modules.common.domain.entity.UserEntity;
import com.lfy.modules.blog.domain.dto.LoginDTO;
import com.lfy.modules.blog.domain.vo.auth.LoginVO;
import com.lfy.modules.blog.service.UserService;
import com.lfy.modules.common.domain.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AuthController {

    @Resource
    private UserService userService;
    @Resource
    private HomeDetailService homeDetailService;



    @PostMapping("/login")
    @NoNeedLogin
    public R<LoginVO> login(@RequestBody @Validated LoginDTO loginDTO, HttpServletResponse response){
        return userService.login(loginDTO,response);
    }

    /**
     * 修改密码
     * @param dto dto
     * @param userEntity userEntity
     * @return R
     */
    @PostMapping("/modify/password")
    public R<Void> modifyPassword(@RequestBody @Validated PwdDTO dto,@AutoUser UserEntity userEntity){

        return this.userService.modifyPassword(dto,userEntity);
    }
    /**
     * 用户菜单路由
     */
    @GetMapping("/getRoute")
    public R<?> getRoute(@AutoUser UserEntity userEntity){
       return userService.getRoute(userEntity);

    }

    /**
     * 获取用户列表
     * @param pageSize 页大小
     * @param pageNum 页码
     * @param name key
     * @return R
     */
    @GetMapping("/getUserList")
    @Authentication("sys:user:get")
    public R<PageResultVO<UserListVO>> getUserList(@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                                   @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                                   String name){
        if(pageSize> PageConstant.MAX_PAGE_SIZE){
            return R.error(BaseEnum.commonEnum.ERROR_PAGE_SIZE);
        }
        return userService.getUserList(pageNum,pageSize,name);
    }

    /**
     * 根据userId更改角色
     */
    @PostMapping("/modifyUserRoleByUserId")
    @Authentication("sys:user:update:role")
    public R<Void> modifyUserRoleByUserId(@RequestBody @Validated ModifyUserRoleDTO dto){
        return this.userService.modifyUserRoleByUserId(dto);
    }
    /**
     * 冻结用户
     */

    @PostMapping("/freezeUser")
    @Authentication("sys:user:update:freeze")
    public R<Void> freezeUser(@RequestBody @Validated ModifyFreezeUserDTO dto){
        return this.userService.freezeUser(dto);
    }
    /**
     * 创建用户
     */

    @PostMapping("/createUser")
    @Authentication("sys:user:create")
    public R<Void> createUser(@RequestBody @Validated(SaveGroup.class) UserDTO dto ){
        String rePassword = dto.getRePassword().trim();
        String password = dto.getPassword().trim();
        if (!rePassword.equals(password)){
            return R.error("两次密码输入不一致");
        }
        return this.userService.createUser(dto);
    }

    /**
     * 修改用户
     * @return R
     */
    @PostMapping("/modifyUser")
    @Authentication("sys:user:update")
    public R<Void> modifyUser(@RequestBody @Validated(UpdateGroup.class) UserDTO dto){
        boolean isPasswordEmpty1 = StringUtils.isBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getRePassword());
        boolean isPasswordEmpty2 = StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isBlank(dto.getRePassword());
       if(isPasswordEmpty1 || isPasswordEmpty2){
           return R.error("密码和确认密码必须同时为空或同时存在");
       }
       if(StringUtils.isNotBlank(dto.getPassword()) && StringUtils.isNotBlank(dto.getRePassword())){
           if(!dto.getPassword().trim().equals(dto.getRePassword().trim())){
               return R.error("两次密码输入不一致");
           }
       }
            return this.userService.modifyUser(dto);
    }
    @GetMapping("/checkUrl")
    public R<Void> getUserByUrl(@RequestParam(value = "url") String url,Long userId){
        LambdaQueryWrapper<UserEntity> userEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userEntityLambdaQueryWrapper.eq(UserEntity::getUrl,url);

        //查询是否存在
        UserEntity one = this.userService.getOne(userEntityLambdaQueryWrapper);
        if(Objects.isNull(one)){
            return R.success();
        }else if(one.getId().equals(userId)){
            return R.success();
        }

        return R.error("该url已被占用");
    }
    @PostMapping("/deleteUser")
    @Authentication("sys:user:delete")
    public R<Void> deleteUser(@RequestParam(value = "userId") Long userId) {
        return this.userService.deleteUser(userId);
    }
    /**
     * 获取全部用户名字和id
     */
    @GetMapping("/getAllUserNameAndId")
    @Authentication("sys:send:user:letter")
    public R<List<UserEntity>> getAllUserNameAndId(@AutoUser UserEntity userEntity){
        List<UserEntity> list = this.userService.list(new LambdaQueryWrapper<UserEntity>().select(UserEntity::getId,UserEntity::getUsername));
        List<UserEntity> result = list.stream().filter(item -> !item.getId().equals(userEntity.getId())).collect(Collectors.toList());
        return R.success(result);
    }
}
